package cn.lbd;

import org.apache.zookeeper.*;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class UniqueID implements Watcher{
    private CountDownLatch countDownLatch = new CountDownLatch(1);
    private ZooKeeper zooKeeper = null;
    private String IP = "39.97.191.1:2181";
    private String uniqueID = "/unique";

    @Override
    public void process(WatchedEvent event) {
        if (event.getType() == Watcher.Event.EventType.None) { //通知状态被修改时，事件类型一定是None
            if (event.getState() == Watcher.Event.KeeperState.SyncConnected) {
                System.out.println("连接成功");
                countDownLatch.countDown();
            }else if (event.getState() == Watcher.Event.KeeperState.Disconnected) {
                System.out.println("断开连接");
            }else if (event.getState() == Watcher.Event.KeeperState.Expired) {
                System.out.println("会话超时");
                try {
                    zooKeeper = new ZooKeeper(IP,5000,this);//超时就重新连接
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }else if (event.getState() == Watcher.Event.KeeperState.AuthFailed) {
                System.out.println("授权失败");
            }
        }
    }

    public UniqueID() {
        try {
            zooKeeper = new ZooKeeper(IP,5000,this);
            countDownLatch.await();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String get() {
        String path = "";
        try {
            path = zooKeeper.create(uniqueID,new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return path;
    }

    public static void main(String[] args) throws InterruptedException {
        UniqueID uniqueID = new UniqueID();
        for (int i = 0; i < 5; i++) {
            System.out.println(uniqueID.get());
        }
        TimeUnit.SECONDS.sleep(10);
    }
}
